package vn.intelsoft.vlogvn;

import java.util.List;

import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubeStandalonePlayer;

import vn.intelsoft.vlogvn.adapter.VlogAdapter;
import vn.intelsoft.vlogvn.db.DbAdapter;
import vn.intelsoft.vlogvn.instance.Instance;
import vn.intelsoft.vlogvn.instance.Log;
import vn.intelsoft.vlogvn.instance.Rest;
import vn.intelsoft.vlogvn.instance.Vlog;
import vn.intelsoft.vlogvn.instance.Vlogger;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;

public class VlogActivity extends BaseActivity implements OnItemClickListener, OnClickListener {

	private RelativeLayout layoutNotConnection, layoutLoading, layoutVlog;
	private List<Vlog> vlogs;
	private ListView listView;
	private String url;
	private boolean isLoad = true;
	private Fragment mContent;
	private List<Vlogger> vloggers;

	public VlogActivity() {
		super(R.string.main_activity);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		overridePendingTransition(R.anim.slide_in_from_right, R.anim.stack_push);
		// if (savedInstanceState != null)
		// mContent = getSupportFragmentManager().getFragment(
		// savedInstanceState, "mContent");

		setContentView(R.layout.activity_vlog);
		init();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		overridePendingTransition(R.anim.stack_pop, R.anim.slide_out_to_right);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if (isLoad) {
			getData();
		}
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		Log.i("onDestroy");
	}

	private void init() {
		Bundle bundle = getIntent().getExtras();

		String name = bundle.getString("name");
		getSupportActionBar().setTitle(name);

		String username = bundle.getString("username");
		url = getResources().getString(R.string.url_start) + username +getResources().getString(R.string.url_end);

		Log.i(url);
		
		layoutNotConnection = (RelativeLayout) VlogActivity.this
				.findViewById(R.id.layout_not_connection);
		layoutVlog = (RelativeLayout) VlogActivity.this
				.findViewById(R.id.layout_vlog);
		layoutLoading = (RelativeLayout) VlogActivity.this
				.findViewById(R.id.layout_loading);
		listView = (ListView) this.findViewById(R.id.list);
		listView.setOnItemClickListener(this);
		registerForContextMenu(listView);
	}

	private void getData() {
		layoutNotConnection.setVisibility(View.INVISIBLE);
		layoutLoading.setVisibility(View.VISIBLE);
		if (Instance.isNetworkAvailable(this)) {
			new getVlogs().execute();
		} else {
			layoutNotConnection.setVisibility(View.VISIBLE);
			layoutNotConnection.setOnClickListener(this);
		}
	}

	private class getVlogs extends AsyncTask<Void, Void, Void> {

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			layoutLoading.setVisibility(View.VISIBLE);
		}

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			String response = Rest.getJsonString(url);
			vlogs = Rest.getVlogFromJSON(response);

			String response1 = Rest.getJsonString(getResources().getString(R.string.xxx));
			vloggers = Rest.getVlogger(response1);
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);

			layoutLoading.setVisibility(View.INVISIBLE);
			layoutVlog.setVisibility(View.VISIBLE);
			// ListAdapter adapter = new ListAdapter(VlogActivity.this,
			// vloggers);
			VlogAdapter adapter = new VlogAdapter(VlogActivity.this, vlogs);
			listView.setAdapter(adapter);
			createSlideMenu(vloggers);
			isLoad = false;
		}

	}

	private void createSlideMenu(List<Vlogger> vloggers) {
		if (mContent == null)
			mContent = new SlideMenuFragment(vloggers);
		FragmentTransaction t = this.getSupportFragmentManager()
				.beginTransaction();
		t.replace(R.id.menu_frame, mContent);
		try {
			t.commit();
		} catch (Exception e) {
			Log.e(e.getMessage());
		}
	}

//	@Override
	public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
		Vlog vlog = vlogs.get(position);
		Intent it = new Intent(VlogActivity.this, PlayerActivity.class);
		it.putExtra("id", vlog.vlogId);
		startActivity(it);

		// youtubePlayer(vlog.vlogId);
	}

	private void youtubePlayer(String id) {
		Intent localIntent = YouTubeStandalonePlayer.createVideoIntent(this,
				"AIzaSyDiUH1TwlOb5AAT35HXEWRIUQIZwg0B7dI", id, 0, true, false);
		if (localIntent != null) {
			if (canResolveIntent(localIntent)) {
				// startActivityForResult(localIntent, 1);
				startActivity(localIntent);
			}
		} else {
			YouTubeInitializationResult.SERVICE_MISSING.getErrorDialog(this, 2)
					.show();
			return;
		}
	}

	private boolean canResolveIntent(Intent paramIntent) {
		List localList = getPackageManager().queryIntentActivities(paramIntent,
				0);
		boolean bool1 = false;
		if (localList != null) {
			boolean bool2 = localList.isEmpty();
			bool1 = false;
			if (!bool2)
				bool1 = true;
		}
		return bool1;
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		getMenuInflater().inflate(R.menu.menu, menu);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		AdapterContextMenuInfo adapterinfo = (AdapterContextMenuInfo) item
				.getMenuInfo();
		Vlog vlog = vlogs.get(adapterinfo.position);

		switch (item.getItemId()) {
		case R.id.addtofavorite:
			DbAdapter db = new DbAdapter(VlogActivity.this);
			List<Vlog> vlogs = db.getAllVlog();
			boolean isExist = false;
			for (int i = 0; i < vlogs.size(); i++) {
				if (vlog.vlogId.equalsIgnoreCase(vlogs.get(i).vlogId)) {
					isExist = true;
					break;
				}
			}
			if (!isExist) {
				db.insert(vlog);
				Toast.makeText(VlogActivity.this, "Đã thêm vào yêu thích!",
						Toast.LENGTH_SHORT).show();
			} else {
				Toast.makeText(VlogActivity.this, "Đã có trong yêu thích!",
						Toast.LENGTH_SHORT).show();
			}

			break;
		case R.id.share:
			Intent localIntent = new Intent();
			localIntent.setAction("android.intent.action.SEND");
			localIntent.putExtra("android.intent.extra.SUBJECT",
					"Share...");
			localIntent.putExtra("android.intent.extra.TEXT",
					getResources().getString(R.string.url_share) + vlog.vlogId);
			localIntent.setType("text/plain");
			startActivity(Intent.createChooser(localIntent, "Send to..."));
			break;
		default:
			break;
		}
		return false;
	}

	@Override
	public boolean onOptionsItemSelected(
			com.actionbarsherlock.view.MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
			return true;
		case R.id.action_favorite:
			Intent it = new Intent(VlogActivity.this, FavoriteActivity.class);
			it.putExtra("name", vloggers.get(1).name);
			it.putExtra("username", vloggers.get(1).username);
			VlogActivity.this.startActivity(it);
			return true;
		}

		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onClick(View v) {
		if(v.getId() == R.id.layout_not_connection){
			getData();
		}
		
	}

}
